import fs from 'fs';
import path from 'path';
import KoaRouter from 'koa-router';


export class RouterRegister {

    basePath: string = './controllers';

    constructor(base = './controllers') {
        this.basePath = base;
    }

    routerRegister(): any[] {
        const basePath = path.join(__dirname, this.basePath);
        const routers = this.getControllers(basePath);
        const routerResult = [];

        routers.forEach((routerPath: string) => {
            let currentRouter = require(routerPath);
            if (currentRouter instanceof KoaRouter) {
                routerResult.push(currentRouter.routes(), currentRouter.allowedMethods());
            } else {
                Object.values(currentRouter).forEach(itemRouter => {
                    if (itemRouter instanceof KoaRouter) {
                        routerResult.push(itemRouter.routes(), itemRouter.allowedMethods());
                    }
                });
            }
        });
        return routerResult;
    }
    getControllers(controllerPath: string) {
        const routers: string[] = [];
        if (!fs.existsSync(controllerPath)) {
            return [];
        }
        const files = fs.readdirSync(controllerPath);
        files.forEach((currentFile) => {
            const routerFile = path.join(controllerPath, currentFile);
            if (fs.statSync(routerFile).isDirectory()) {
                routers.push(...this.getControllers(routerFile));
            } else {
                routers.push(routerFile);
            }
        });
        return routers;
    }
}